<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>侠客先锋</title>
  <link rel="stylesheet" href="style.css">
  <script>
    process.env.LANG = 'zh_CN.UTF-8';
    process.env.LC_ALL = 'zh_CN.UTF-8';
  </script>
  <style>
    
  </style>
</head>
<body>
  <!-- 边框元素 -->
  <div class="resize-border top"></div>
  <div class="resize-border right"></div>
  <div class="resize-border bottom"></div>
  <div class="resize-border left"></div>
  
  <!-- 四个角 -->
  <div class="resize-corner top-left"></div>
  <div class="resize-corner top-right"></div>
  <div class="resize-corner bottom-left"></div>
  <div class="resize-corner bottom-right"></div>

  <!-- 顶部工具栏 -->
  <div class="toolbar">
    <div class="tab-area">
      <div id="tab-bar">
        <!-- 多开按钮将被移到这里，通过 JavaScript 动态管理 -->
      </div>
    </div>
    <div class="toolbar-controls">
      <button class="menu-toggle" onclick="toggleMenu()">☰</button>
    </div>
  </div>

  <div id="container">
    <div id="tab-container"></div>
  </div>

  <!-- 菜单 -->
  <div class="side-controls hidden">
    <button class="side-button" onclick="reload()"></button>
    <button class="side-button" onclick="clearCache()"></button>
    <button class="side-button" onclick="minimizeWindow()"></button>
    <button class="side-button" onclick="closeWindow()"></button>
    <button class="side-button" onclick="showResizeConfirmDialog()" title="测试对话框"></button>
  </div>

  <!-- 再加载主脚本 -->
  <script src="script.js"></script>
  <script>

    if (process.platform === 'win32') {
      process.env.LANG = 'zh_CN.UTF-8';
      process.env.LC_ALL = 'zh_CN.UTF-8';
    }

    // 添加全局的编码处理函数
    window.decodeFilePath = function(path) {
      try {
        return decodeURIComponent(path);
      } catch (e) {
        console.error('解码路径失败:', e);
        return path;
      }
    };

    // 设置初始窗口大小和背景
    window.onload = function() {
      const win = nw.Window.get();
      
      // 设置窗口背景为黑色
      win.backgroundColor = "#000000";
      
      var currentWidth = 0;
      var currentHeight = 0;

      // 默认期望尺寸
      const screen = window.screen;
      console.log('当前分辨率？:w=', screen.availWidth, ',h=', screen.availHeight);
      const defaultWidth = Math.floor(screen.availWidth * 0.95);//1904;
      const defaultHeight = Math.floor(screen.availHeight * 0.9);//914;
      
      // 从 package.json 读取最小尺寸
      const manifest = nw.App.manifest;
      const minWidth = manifest.window.min_width || 800;
      const minHeight = manifest.window.min_height || 600;
      
      // 居中窗口的函数
      function centerWindow(width, height) {
        const screen = window.screen;
        const x = Math.floor((screen.availWidth - width) / 2);
        const y = Math.floor((screen.availHeight - height) / 2);
        win.moveTo(Math.max(0, x), Math.max(0, y));
        win.resizeTo(width, height);
      }
      function handleMouseUp() {
        
        // 检查窗口尺寸是否发生了变化
          console.log('窗口尺寸发生变化，显示确认对话框');
          showResizeConfirmDialog();
      }
      
      // 尝试读取上次保存的窗口大小
      const savedSize = {
        width: parseInt(localStorage.getItem('windowWidth')),
        height: parseInt(localStorage.getItem('windowHeight'))
      };
      
      // 决定使用哪个尺寸
      let targetWidth, targetHeight;
      
      if (savedSize.width && savedSize.height) {
        // 直接使用保存的尺寸，不做屏幕大小验证
        targetWidth = Math.max(savedSize.width, minWidth);
        targetHeight = Math.max(savedSize.height, minHeight);
        console.log('使用上次保存的尺寸:', targetWidth, 'x', targetHeight);
      } else {
        // 首次运行，使用默认尺寸
        targetWidth = defaultWidth;
        targetHeight = defaultHeight;
        console.log('使用默认尺寸:', targetWidth, 'x', targetHeight);
      }
      
      // 仅在启动时居中显示窗口
      centerWindow(targetWidth, targetHeight);
      
      // 处理窗口尺寸变化的函数
      function handleWindowSizeChange(eventType) {
        const newWidth = window.outerWidth;
        const newHeight = window.outerHeight;
        
        if (currentWidth !== newWidth || currentHeight !== newHeight) {
          if (currentWidth !== 0 && currentHeight !== 0) {
            handleMouseUp();
          }
          currentWidth = newWidth;
          currentHeight = newHeight;
          localStorage.setItem('windowWidth', currentWidth);
          localStorage.setItem('windowHeight', currentHeight);
          console.log(`保存${eventType}后的窗口大小:`, currentWidth, 'x', currentHeight);
        }
      }
      
      // 监听窗口大小变化
      let resizeTimeout;
      win.on('resize', function() {
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(() => {
          handleWindowSizeChange('resize');
        }, 500);
      });
      
      // 监听窗口最大化事件
      win.on('maximize', function() {
        console.log('窗口已最大化');
        setTimeout(() => {
          handleWindowSizeChange('最大化');
        }, 100);
      });
      
      // 监听窗口还原事件
      win.on('restore', function() {
        console.log('窗口已还原');
        setTimeout(() => {
          handleWindowSizeChange('还原');
        }, 100);
      });
    };

    // 添加拖拽调整大小功能
    function initResize() {
      const win = nw.Window.get();
      const borders = document.querySelectorAll('.resize-border, .resize-corner');

      borders.forEach(border => {
        border.addEventListener('mousedown', (e) => {
          e.preventDefault();
          const direction = border.className.split(' ')[1];
          
          const startX = e.screenX;
          const startY = e.screenY;
          const startWidth = window.outerWidth;
          const startHeight = window.outerHeight;
          const startLeft = window.screenX;
          const startTop = window.screenY;

          function handleMouseMove(e) {
            // 添加节流以减少闪烁
            if (!window.requestAnimationFrame) {
              handleResize(e);
            } else {
              requestAnimationFrame(() => handleResize(e));
            }
          }

          function handleResize(e) {
            const deltaX = e.screenX - startX;
            const deltaY = e.screenY - startY;

            switch(direction) {
              case 'left':
                win.resizeTo(startWidth - deltaX, startHeight);
                win.moveTo(startLeft + deltaX, startTop);
                break;
              case 'right':
                win.resizeTo(startWidth + deltaX, startHeight);
                break;
              case 'top':
                win.resizeTo(startWidth, startHeight - deltaY);
                win.moveTo(startLeft, startTop + deltaY);
                break;
              case 'bottom':
                win.resizeTo(startWidth, startHeight + deltaY);
                break;
              case 'top-left':
                win.resizeTo(startWidth - deltaX, startHeight - deltaY);
                win.moveTo(startLeft + deltaX, startTop + deltaY);
                break;
              case 'top-right':
                win.resizeTo(startWidth + deltaX, startHeight - deltaY);
                win.moveTo(startLeft, startTop + deltaY);
                break;
              case 'bottom-left':
                win.resizeTo(startWidth - deltaX, startHeight + deltaY);
                win.moveTo(startLeft + deltaX, startTop);
                break;
              case 'bottom-right':
                win.resizeTo(startWidth + deltaX, startHeight + deltaY);
                break;
            }
          }

          

          document.addEventListener('mousemove', handleMouseMove);
          document.addEventListener('mouseup', handleMouseUp);
        });
      });
    }

    // 初始化
    document.addEventListener('DOMContentLoaded', initResize);
    
    // 显示窗口拉伸确认对话框
    function showResizeConfirmDialog() {
      console.log('显示确认对话框');
      
      // 创建遮罩层
      const overlay = document.createElement('div');
      overlay.id = 'resize-dialog-overlay';
      overlay.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background: rgba(0, 0, 0, 0.7);
        z-index: 999999;
        display: flex;
        align-items: center;
        justify-content: center;
        pointer-events: auto;
      `;
      
      // 创建对话框
      const dialog = document.createElement('div');
      dialog.id = 'resize-dialog';
      dialog.style.cssText = `
        background: #2d2d2d;
        border: 2px solid #555;
        border-radius: 8px;
        padding: 24px;
        max-width: 400px;
        width: 90%;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
        font-family: Arial, sans-serif;
        z-index: 1000000;
        position: relative;
      `;
      
      // 对话框标题
      const title = document.createElement('div');
      title.textContent = '窗口变化';
      title.style.cssText = `
        color: #fff;
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 16px;
        text-align: center;
      `;
      
      // 对话框内容
      const content = document.createElement('div');
      content.textContent = '是否刷新游戏？';
      content.style.cssText = `
        color: #ccc;
        font-size: 14px;
        margin-bottom: 24px;
        text-align: center;
      `;
      
      // 按钮容器
      const buttonContainer = document.createElement('div');
      buttonContainer.style.cssText = `
        display: flex;
        gap: 12px;
        justify-content: center;
      `;
      
      // 确定按钮
      const confirmBtn = document.createElement('button');
      confirmBtn.textContent = '确定';
      confirmBtn.style.cssText = `
        background: #4CAF50;
        color: white;
        border: none;
        padding: 10px 24px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: background 0.2s;
      `;
      confirmBtn.addEventListener('mouseenter', () => {
        confirmBtn.style.background = '#45a049';
      });
      confirmBtn.addEventListener('mouseleave', () => {
        confirmBtn.style.background = '#4CAF50';
      });
      confirmBtn.addEventListener('click', () => {
        // 刷新所有webview
        const webviews = document.querySelectorAll('webview');
        webviews.forEach(webview => {
          webview.reload();
        });
        document.body.removeChild(overlay);
      });
      
      // 取消按钮
      const cancelBtn = document.createElement('button');
      cancelBtn.textContent = '取消';
      cancelBtn.style.cssText = `
        background: #666;
        color: white;
        border: none;
        padding: 10px 24px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: background 0.2s;
      `;
      cancelBtn.addEventListener('mouseenter', () => {
        cancelBtn.style.background = '#555';
      });
      cancelBtn.addEventListener('mouseleave', () => {
        cancelBtn.style.background = '#666';
      });
      cancelBtn.addEventListener('click', () => {
        document.body.removeChild(overlay);
      });
      
      // 组装对话框
      buttonContainer.appendChild(confirmBtn);
      buttonContainer.appendChild(cancelBtn);
      dialog.appendChild(title);
      dialog.appendChild(content);
      dialog.appendChild(buttonContainer);
      overlay.appendChild(dialog);
      
      // 添加到页面
      document.body.appendChild(overlay);
      console.log('对话框已添加到页面');
      
      // 点击遮罩层关闭对话框
      overlay.addEventListener('click', (e) => {
        if (e.target === overlay) {
          document.body.removeChild(overlay);
        }
      });
      
      // ESC键关闭对话框
      const handleEsc = (e) => {
        if (e.key === 'Escape') {
          document.body.removeChild(overlay);
          document.removeEventListener('keydown', handleEsc);
        }
      };
      document.addEventListener('keydown', handleEsc);
    }
  </script>


</body>
</html>